package com.kevin.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import lombok.extern.log4j.Log4j;

import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

@Log4j
public class ConfigProperties {
    public static final String WORDSET = "wordset";
    public static final String DICTORY = "dictory";
    public static final String TABLELIST = "tablelist"; // 搜索到的table
    public static final String HELP_DESP = "helpDesp";
    public static final String EXTEND_JAVATYPE = "extendjavatype";// 扩展java类型

    public static final String CACHE_TABLE_COL = "tableColCache"; // 根据表搜索的字段
    public static final String CACHE_STEP1_TABLE = "step1tableCache"; // 第一步搜索表
    public static final String CACHE_COMMON_WORDS = "commonWordsCache"; // 常用字

    public static PropertiesConfiguration config;
    public static PropertiesConfiguration cacheConfig;
    static {
        AbstractConfiguration.setDefaultListDelimiter(';');// 默认分隔符
        try {
            config = new PropertiesConfiguration("wscfg.properties");
            config.setReloadingStrategy(new FileChangedReloadingStrategy());// 文件发生改变时重新加载
            File cacheFile = new File(PathUtil.getProjectAbsolutePath() + "cache.properties");
            if (!cacheFile.exists()) {
                cacheFile.createNewFile();
            }
            cacheConfig = new PropertiesConfiguration("cache.properties");
            cacheConfig.setReloadingStrategy(new FileChangedReloadingStrategy());// 文件发生改变时重新加载
        } catch (ConfigurationException e) {
            log.error("获取系统属性出错！", e);
        } catch (IOException e) {
            log.error("创建缓存文件出错！", e);
        }
    }

    public static void setProperty(String key, String value) {
        config.setProperty(key, value);
        try {
            config.save();
        } catch (ConfigurationException e) {
            log.error("保存失败", e);
        }
    }

    public static String getString(String key) {
        return config.getString(key, "");
    }

    public static String getString(String key, String value) {
        return config.getString(key, value);
    }

    public static List<String> getList(String key) {
        List<String> returnDataList = new ArrayList<String>();
        List<Object> cons = config.getList(key);
        if (cons != null) {
            returnDataList = cons.stream().map(obj -> obj.toString()).collect(Collectors.toList());
        }
        return returnDataList;
    }

    public static void save() {
        try {
            config.save();
        } catch (ConfigurationException e) {
            log.error("保存失败", e);
        }
    }
}